package studio.wetrack.mongo.interfacelog;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author linzh
 * @date 2018-09-29 10:24
 */
public class LogDatabase {
    MongoDatabase mongoDatabase;
    Map<String, MongoCollection> collectionMap = new HashMap<>();

    public LogDatabase(String username, String password, String host, Integer port, String database) {
        MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());
        MongoClient mongoClient = MongoClients.create(
                MongoClientSettings.builder()
                        .applyToClusterSettings(builder ->
                                builder.hosts(Arrays.asList(new ServerAddress(host, port))))
                        .credential(credential)
                        .build());
        mongoDatabase = mongoClient.getDatabase(database);
    }

    public MongoCollection<Document> getCollection(String path) {
        MongoCollection<Document> collection = collectionMap.get(path);
        if (collection == null) {
            synchronized (collectionMap) {//concurrentHashmap不能保证同一个path的collection不会被后来者替代
                if((collection = collectionMap.get(path))==null){
                    collection = mongoDatabase.getCollection(path);
                    collectionMap.put(path, collection);
                }
            }
        }
        return collection;
    }
}
